package ConcurrentProgramming;


import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * 带返回值的线程 之前的Thread和Runnable都是没有返回值的
 * Callable接口是带有返回值的线程接口 Callable<T> 泛型 T 是该线程的返回值类型
 * 必须使用ExecotorService.submit()方法进行执行
 * Runnable run()方法没有抛出异常
 * Callable call()方法会主动抛出异常，并且带有返回值
 */
@SuppressWarnings("all")
public class CallableDemo implements Callable<String> {
    private int id;
    public CallableDemo(int id) {
        this.id = id;
    }
    @Override
    public String call() throws Exception {
        TimeUnit.MILLISECONDS.sleep(1000);
        return "result of CallableDemo----" + id;
    }

    /*@Override
    public void run() {

    }*/
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ArrayList<Future<String>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(new CallableDemo(i)));
        }
        for (Future<String> future : futures) {
            try {
                future.get(); // 调用get方法时是线程阻塞的
                System.out.println(future.get()); // get方法获取线程的返回值
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } finally {
                executorService.shutdown();
            }
        }
        executorService.shutdown();
    }
}
